package com.lajiaomian.springbootruijiwaimai.controller;

import com.lajiaomian.springbootruijiwaimai.common.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.UUID;

/**
 * @author lajiaomian
 * @create 2022-08-13-21:25
 */
@RestController
@RequestMapping("/common")
@Slf4j
public class CommonController {
    @Value("${UpDownFile.path}")
    private String destPath;
    /**
     * 文件上传功能
     * @param file
     * @return
     */
    @PostMapping("/upload")
    public R<String> upload(MultipartFile file){
        log.info("进行文件上传...{}",file);
        //先获取原始文件名
        String originalFilename = file.getOriginalFilename();
        //获取上传文件的后缀
        String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
        //使用UUID+后缀拼接成目标文件名
        String destName= UUID.randomUUID()+suffix;
        try {
            file.transferTo(new File(destPath + destName));
        } catch (IOException e) {
            e.printStackTrace();
        }
        return R.success(destName);
    }

    /**
     * 下载功能
     * @param name
     * @param response
     */
    @GetMapping("/download")
    public void download(String name, HttpServletResponse response){
        try {
            //获取输入流的文件地址
            FileInputStream fis = new FileInputStream(new File(destPath+name));
            //通过response设置输出流，输出到浏览器
            ServletOutputStream os = response.getOutputStream();
            //下面这个是固定的，对于jpg文件
            response.setContentType("image/jpeg");
            //下面的文件读取输出的过程
            byte[] bytes = new byte[1024];
            int len = 0;
            while((len=fis.read(bytes))!=-1){
                os.write(bytes,0,len);
                os.flush();
            }
            //关闭流
            fis.close();
            os.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
